<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 员工页头 -->
      <page-header>
        <template #left>
          <span>总计数{{ total }}</span>
        </template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('upload-excel')"
            >excel导入</el-button
          >
          <el-button type="danger" size="small" @click="handleDownLoad"
            >excel导出当前页</el-button
          >
          <el-button type="danger" size="small" @click="handleDownLoadAll"
            >excel导出所有</el-button
          >
          <el-button type="primary" size="small" @click="showDialog = true"
            >新增员工</el-button
          >
        </template>
      </page-header>
      <!-- 表格 -->
      <el-card style="margin-top: 10px">
        <el-table :data="employeeList" border stripe width="100%">
          <el-table-column
            label="序号"
            width="85"
            :index="indexMethod"
          ></el-table-column>
          <el-table-column
            label="姓名"
            prop="username"
            width="80"
          ></el-table-column>
          <el-table-column label="头像" width="120"
            ><template #default="{ row }"
              ><img
                :src="row.staffPhoto"
                width="80"
                v-imgerror="defaultAvatar"
                @click="handleQrCode(row.staffPhoto)" /></template
          ></el-table-column>
          <el-table-column
            label="手机号"
            prop="mobile"
            width="50"
          ></el-table-column>
          <el-table-column
            label="工号"
            prop="workNumber"
            width="120"
          ></el-table-column>
          <el-table-column label="聘用形式" width="85">
            <template #default="{ row }">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column
            label="部门"
            prop="departmentName"
            width="120"
          ></el-table-column>
          <el-table-column
            label="入职时间"
            prop="timeOfEntry"
            width="200"
          ></el-table-column>
          <el-table-column label="账户状态" width="120"
            ><template #default="{ row }">
              {{ formatEnableState(row.enableState) }}
            </template></el-table-column
          >
          <el-table-column label="操作" fixed="right" width="300">
            <template #default="{ row }">
              <el-button
                type="text"
                @click="$router.push(`/employees/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button type="text" @click="handleOpen(row.id)"
                >角色</el-button
              >
              <el-button type="text" @click="handleDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 新增员工 -->
      <add-employee
        :showDialog.sync="showDialog"
        @add-success="getEmployeeList"
      />
      <!-- 分页 -->
      <el-pagination
        :total="total"
        :page-size="query.size"
        :current-page="query.page"
        :page-sizes="[3, 2, 8, 10]"
        layout="total,sizes,prev,pager,next,jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-dialog title="二维码" :visible="isShow" @close="isShow = false">
        <!-- 这里展示二维码
      画布 -->
        <canvas ref="qrCodeRef" />
      </el-dialog>

      <!-- 分配 -->
      <el-dialog title="分配角色" :visible="isShow2" @close="handleClose">
        <el-checkbox-group v-model="checkedRoleList">
          <!-- label两个用途  1、展示文本  2、给v-model提供数据 -->
          <el-checkbox
            v-for="item in rolesList"
            :key="item.id"
            :label="item.id"
            >{{ item.name }}</el-checkbox
          >
        </el-checkbox-group>
        <template #footer>
          <el-button size="small" @click="handleClose">取消</el-button>
          <el-button size="small" type="primary" @click="handleAssign"
            >确定</el-button
          >
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getEmployeeListAPI,
  delEmloyeeAPI,
  getEmployeeInfoAPI,
  assignRoleAPI,
} from "@/api/employees";
import { getUerRoleAPI } from "@/api/setting";
// 模块化语法导入默认头像
import defaultAvatar from "@/assets/common/456.jpg";
//导入常量模块
import obj from "@/constant/employees";
//导入组件
import AddEmployee from "./add-employee.vue";
import { export_json_to_excel } from "@/vendor/Export2Excel";
// excel文件的导入导出
import QrCode from "qrcode";
export default {
  components: { AddEmployee },
  name: "EmployeesView",
  data() {
    return {
      // 角色列表
      rolesList: [],
      checkedRoleList: [],
      defaultAvatar,
      // 员工列表
      employeeList: [],
      total: 0,
      query: {
        page: 1,
        size: 5,
      },
      //控制新赠员工的显示
      showDialog: false,
      isShow: false,
      isShow2: false,
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    // 获取员工列表
    async getEmployeeList() {
      //发请求获取列表
      const resp = await getEmployeeListAPI(this.query);
      //结构
      const { rows, total } = resp.data;
      //赋值
      this.employeeList = rows;
      this.total = total;
    },
    //自定义下标
    indexMethod(index) {
      //规则  当前页的数据序号 + 1 +（当前页码 - 1）* 每页条数
      return index + 1 + 1(this.query.page - 1) * this.query.size;
    },
    // 格式化聘用形式
    formatEmployment(formOfEmployment) {
      // 1->正式
      // 2->非正式
      // 3->实习
      // 4->钟点工
      // const obj = {
      //   1: "正式gong",
      //   2: "非正式gong",
      //   3: "实习gong",
      //   4: "钟点gong",
      // };
      const item = obj.hireType.find((item) => item.id === formOfEmployment);
      return item ? item.value : "未知";
    },
    //格式化在职状态
    formatEnableState(enableState) {
      //根据enableState去wokingState中查找
      const item = obj.workingState.find((item) => item.id === enableState);
      return item ? item.value : "未知";
    },
    //处理每页条数改变时
    handleSizeChange(val) {
      //选择条数同步到query.size中
      this.query.size = val;
      this.getEmployeeList();
    },
    handleCurrentChange(val) {
      (this.query.page = val), this.getEmployeeList();
    },
    //删除员工
    async handleDel(employeeId) {
      try {
        //询问
        await this.$confirm("此人是反贼，确定要做掉他吗", "暗杀请求", {
          type: "warning",
        });
        //确定
        // 最后一页问题
        if (this.query.page > 1 && this.employeeList.length === 1) {
          this.query.page--;
        }
        //发请求
        await delEmloyeeAPI(employeeId);
        //获取列表
        this.getEmployeeList();
        //给提示
        this.$message.success("删除成功");
      } catch (err) {}
    },
    // 下载当前页
    handleDownLoad() {
      const header = [
        "姓名",
        "部门",
        "手机号",
        "工号",
        "聘用形式",
        "入职日期",
        "转正日期",
      ];
      const headerRalation = {
        手机号: "mobile",
        姓名: "username",
        聘用形式: "formOfEmployment",
        入职日期: "timeOfEntry",
        工号: "workNumber",
        转正日期: "correctionTime",
        部门: "departmentName",
      };
      const data = this.employeeList.map((item) => {
        const arr = [];
        header.forEach((zhKey) => {
          const enKey = headerRalation[zhKey];
          // arr.push(item[enKey]);
          if (enKey === "formOfEmployment") {
            const temp = obj.hireType.find((a) => a.id === +item[enKey]);
            arr.push(temp ? temp.value : "母鸡锕");
          } else {
            arr.push(item[enKey]);
          }
        });
        return arr;
      });
      export_json_to_excel({
        //表头
        header,
        //表体（二维数组）
        data,
        // 文件名
        filename: `${this.$store.state.user.userInfo.companyName}员工列表`,
      });
    },
    // 下载所有
    async handleDownLoadAll() {
      //吧总条数同步到query.size中
      this.query.size = this.total;
      //  重置代码页为1
      this.query.page = 1;
      await this.getEmployeeList();
      this.handleDownLoad();
    },
    //二维码
    handleQrCode(url) {
      if (!url) return;
      this.isShow = true;
      // 点击的图片变为二维码
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.qrCodeRef, url);
      });
      // QrCode.toCanvas(canvas的DOM元素，转换的消息)
    },
    //关闭
    handleClose() {
      this.isShow2 = false;
    },
    //分配角色打开
    async handleOpen(employeeId) {
      this.id = employeeId;
      this.isShow2 = true;
      // 获取徐偶有角色列表
      const resp1 = await getUerRoleAPI({
        page: 1,
        pagesize: this.total,
      });
      // 保存列表
      this.rolesList = resp1.data.rows;
      // 获取当前员工的角色信息
      const resp2 = await getEmployeeInfoAPI(employeeId);
      // 回显（给v-model绑定的角色赋值）
      console.log(resp2);
      this.checkedRoleList = resp2.data.roleIds;
    },
    // 角色分配
    handleAssign() {
      // 发请求（选中角色发送后台）
      assignRoleAPI(this.id, this.checkedRoleList);
      //关闭弹窗
      this.handleClose();
      //成功提示
      this.$message.success("OK了，家人");
    },
  },
};
</script>

<style>
.el-pagination {
  margin-top: 20px;
}
</style>